package com.javabasic.algorithm.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see [1302. 层数最深叶子节点的和 - 力扣（LeetCode）](https://leetcode.cn/problems/deepest-leaves-sum/)
 * @since Created by work on 2022/8/17 22:08
 */
public class DeepestLeavesSum {

    /**
     * 树的层序遍历 BFS
     * @param root
     * @return
     */
    public int deepestLeavesSum(TreeNode root) {
        if (null == root) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        int sum = 0, size;
        while (!queue.isEmpty()) {
            size = queue.size();
            sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                sum += node.val;
            }
        }
        return sum;
    }
}
